/**
 * @description:混入对象
 */
import baseURL from "@/api/baseURL"
import tableApi from "@/api/basic-info-manage/table-config";
import tableColumn from "@/components/tableColumn";

export const mymixin = {
  components: { tableColumn },
  data() {
    return {
      //弹窗是否能修改
      mixDialogDisabled: false,
      nowpage: 1,
      loading: true,
      // 输入框是否可修改true为可修改
      canInput: false,
      // 添加删除修改状态---主要通过此状态来判断调用方法
      nowChanceStau: '',
      // 操作按钮的逻辑及展示数据
      addActive: true,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      editActive: false,
      dialogFormVisible: false,
      // 表格数据
      tableData: [],
      // 表单数据
      formData: {},
      treeData: [],
      image: null,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 总页数
      totalPages: 0,
      allPointList: [],
      rightTableData: [],
      unitTypeId: '',
      unitsList: [],
      deleteFlag: true,
      tagsList: [],
      addformData: {},
      rules: {},
      postName: "",
      // 图片上传
      basicUrl: `${baseURL.webServiceUrl}om/collectionPicture/`,
      // 重置
      reseUrl: `${baseURL.webServiceUrl}om/collectionPicture/`,
      pictureId: '',
      token: "",
      InImgUrl: '',
      funcAppAuthActive: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近一年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }
        ]
      },
      // 地址选择
      selectedOptions: [],
      address: "",
      // 弹出框添加修改
      titleText: null,
      currentRow: null,
      imgList: [],
      // 搜索框的显示与隐藏
      activeName: ''
    }
  },
  created() {
    this.token = sessionStorage.getItem("token");
  },
  watch: {
    nowChanceStau(newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === 'del') {
        this.delmessage('formData')
      }
    }
  },
  computed: {
    headers() {
      return {
        "accessToken": sessionStorage.getItem("token"),
        "organizationNo": sessionStorage.organizationNo,
        "organizationList": sessionStorage.organizationList,
        "databaseName": sessionStorage.databaseName,
        "virtualSystemNo": sessionStorage.virtualSystemNo,
        "sysDataBaseName": "DB_TDW1_OM1"
      }
    }
  },
  methods: {
    handleChange() {
    },
    // select搜索框
    changeSelect() {
      if (this.activeName === '') {
        this.activeName = '1'
      } else if (this.activeName === '1') {
        this.activeName = ''
      }
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({
              'index': i + this.tableData.length - 1
            });
          }
        }
      }
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    // 添加
    add() {
      this.canInput = true;
      this.nowChanceStau = 'add'
      this.formData = {}
      this.image = null;
      this.tagsList = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.basicUrl = this.reseUrl;
      this.postName = ""
      this.InImgUrl = ''
      this.titleText = "添加"
      this.dialogFormVisible = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    // 修改
    edit(data) {
      this.nowChanceStau = 'edit'
      this.basicUrl = this.reseUrl;
      this.titleText = "修改"
      this.dialogFormVisible = true;
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false
      this.mixDialogDisabled = false
      data && this.handleEdit && this.handleEdit(data)
    },
    // 删除
    del() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          this.nowChanceStau = 'del'
          // this.resetActionBar()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          // this.resetActionBar()
          if (this.tableData.length > 0) {
            // alert(1)
            this.$refs.tableData.clearSelection();
          } else if (this.treeData.length > 0) {
            this.$refs.tree.setCheckedKeys([]);
          }
          // this.resetActionBar();
        });
      this.formData = {}
      this.postName = ""
      this.nowChanceStau = "";
      this.canInput = true;
      this.addActive = true;
      // this.delActive = false;
      this.saveActive = false;
      this.editActive = false
      this.cancelActive = false;
    },
    // 取消
    cancel(formData) {
      this.deleteFlag = true;
      this.nowChanceStau = '';
      this.formData = {};
      this.pictureId = '';
      this.basicUrl = "";
      this.rightTableData = [];
      this.tagsList = [];
      this.selectedOptions = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.postName = ""
      this.address = "";
      this.dialogFormVisible = false;
      this.addformData = {}
      this.InImgUrl = ''
      this.imgList = [];
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      if (formData) {
        // console.log(formData)
        this.$refs[formData].resetFields();
        this.$refs.tableData.setCurrentRow()
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = ''
      this.formData = {}
      this.rightTableData = []
      this.image = null;
      this.pictureId = ''
      this.unitTypeId = ''
      this.unitsList = []
      this.InImgUrl = ''
      this.basicUrl = this.reseUrl;
      this.postName = ""
      this.canInput = false;
      this.dialogFormVisible = false;
      this.funcAppAuthActive = false
      this.addActive = true;
      this.delActive = false;
      this.imgList = [];

      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false
    },
    // 列配置
    showColumn() {
      // this.allTableColumn = [...this.formDataLists];
      this.dialogTableColumnVisible = true;
    },
    saveColumn() {
      this.$refs.tableColumn && this.$refs.tableColumn.save()
    },
    cancelColumn(reload) {
      this.dialogTableColumnVisible = false
      reload && this.loadSaveColumn()
    },
    loadSaveColumn() {
      let path = this.$route.path
      // if (['/production-batch-query', '/create-production-batch'].includes(path)) {
      //   path = path + this.batchType
      // }
      // if (this.formDataLists && this.formDataLists.length > 0) {
      //   this.allTableColumn = [...this.formDataLists];
      // }
      // if (this.formDataLists && this.formDataLists.length > 0) {
      //   this.allTableColumn = [...this.formDataLists];
      // }
      // console.log('11111111111111111111')
      tableApi.queryByUrlAndAccountAndOrganizationNo(path).then(res => {
        let fieldContentStr = res.data?.fieldContentStr;
        let fieldContent = fieldContentStr && JSON.parse(fieldContentStr);
        if (fieldContent) {
          let tableColumn = []
          fieldContent.map(el => {
            let index = this.allTableColumn.findIndex(ele => {
              return ele.porp === el.porp
            })
            el.show && tableColumn.push(this.allTableColumn[index])
          })
          this.tableColumn = tableColumn;
          if (this.formDataLists && this.formDataLists.length > 0) {
            this.formDataLists = tableColumn;
          }
          if (this.formDataLists && this.formDataLists.length > 0) {
            this.formDataLists = tableColumn;
          }
        }
      })
    },
    // 表格筛选
    tableUpdate(data, name) {
      // let flag = true;
      // 筛选条件如果已经存在，就更新,注意判别传递过来的数据类型
      if (data.type === "Reset") {
        console.log(data.porp, this.searchObj);
        for (let key in this.searchObj) {
          if (key === data.porp || key === data.selectValue || key === data.porpName) {
            this.$set(this.searchObj, key, undefined);
          }
        }
      } else if (
        data.value !== "" &&
        data.type !== "Reset" &&
        data.type !== "wholeReset"
      ) {
        console.log(data, '____________________________________')
        if (data.selectValue) {
          this.searchObj[data.selectValue] = data?.value;
        } else {
          this.searchObj[data.porp] = data?.value;
        }
        // 如果为耳标或者电子耳标需要，通过data.value获取编号，在返回数据中获取
      } else if (data.type === "wholeReset") {
        this.tableUpStauts = 3;
        for (let key in this.searchObj) {
          this.$set(this.searchObj, key, undefined);
          // }
        }
        setTimeout(() => {
          this.tableUpStauts = 1;
        }, 200);
      }
      this.tableUpdatePlus(data, name)
      this.search();
    },
    // 表格筛选特化处理
    tableUpdatePlus(data, name) {
      console.log(data, name);
    },
    // 时间戳格式化
    formatDateTime(val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "年" + month + "月" + date + "日";
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    // 时间戳格式化
    formatDateTime_(val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      month = month < 10 ? ('0' + month) : month;
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      date = date < 10 ? ('0' + date) : date;
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "-" + month + "-" + date;
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    formatDateTimeMHS(val) {
      if (val) {
        var time = new Date(val);
        var year = time.getFullYear(); // 取得4位数的年份
        var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
        month = month < 10 ? ('0' + month) : month;
        var date = time.getDate(); // 返回日期月份中的天数（1到31）
        date = date < 10 ? ('0' + date) : date;
        var hour = time.getHours(); // 返回日期中的小时数（0到23）
        hour = hour < 10 ? ('0' + hour) : hour;
        var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = time.getSeconds(); // 返回日期中的秒数（0到59）
        second = second < 10 ? ('0' + second) : second;
        return year + "-" + month + "-" + date + ' ' + hour + ':' + minute + ':' + second;
        // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;}
      }
    },
    listfor({
      formDataList = 'formDataList'
  /* 需要插入的数组 为Array进行循环 */,
      porp = ''
  /* 需要插入的值 为Array进行循环 */,
      list = []
  /* 需要插入的数数据 */,
      listName = ["name", "value"]
  /* 字段名 */ }) {
      // console.time('small loop');
      const _this = this
      // 非单个数据
      // console.log(this[formDataList]);

      if (typeof formDataList !== "string") {
        formDataList.forEach((listitem) => {
          // 文本过滤（不知道有用没）
          let livelist = JSON.parse(JSON.stringify(_this[listitem]))
          livelist.forEach((item, index) => {
            if (typeof porp !== "string") {
              porp.forEach((porpitem, porpindex) => {
                if (item.porp === porpitem) {
                  _this.$set(_this[listitem][index], "typeObj", {
                    list: list[porpindex],
                    listName: listName
                  });
                }
              })
            } else {
              if (item.porp === porp) {
                _this.$set(_this[listitem][index], "typeObj", {
                  list: list,
                  listName: listName
                });
              }
            }
          });
        })
      } else {
        _this[formDataList].forEach((item, index) => {
          if (item.porp === porp) {
            _this.$set(_this[formDataList][index], "typeObj", {
              list: list,
              listName: listName
            });
          }
        });
      }
      // console.timeEnd('small loop');
    },
    // 获取日期函数
    getdateBetween(startDate, day) {
      if (!startDate || !day) return '无数据';
      const sDate = Date.parse(startDate);
      const time = sDate + (day * 24 * 60 * 60 * 1000);
      return this.dateToFormattwo(time, 'date');
    },
    // 获取天数函数
    getDaysBetween(startDate, enDate, st = true) {
      if (!startDate || !enDate) return 0;
      const sDate = Date.parse(startDate);
      const eDate = Date.parse(enDate);
      console.log(sDate, eDate)
      if (st) {
        if (sDate > eDate) {
          return 0;
        }
        if (sDate === eDate) {
          return 0;
        }
        const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
        return days;
      } else {
        if (sDate > eDate) {
          return 1;
        }
        if (sDate === eDate) {
          return 1;
        }
        if (sDate < eDate) {
          return 0;
        }
      }
    },
    // 循环过滤树形数组
    filterTreeKey(arr, child = 'child') {
      let newArr = []
      newArr = arr?.map(item => {
        if (item[child].length > 0) {
          item = {
            ...item,
            [child]: this.filterTreeKey(
              item[child]
            )
          }
        } else {
          delete item[child]
        }
        return item
      })
      newArr = newArr?.filter(item => item != null)
      return newArr
    },

  }
}
